package cn.com.acca.ma.common.util;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * HttpClient的工具类
 */
public class HttpClientUtil {

    public static String get(String strUrl) throws MalformedURLException, URISyntaxException {
        return get(strUrl, null);
    }

    public static String get(String strUrl, Map<String, String> headerMap) throws MalformedURLException, URISyntaxException {
        URL url = new URL(strUrl);
        URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);

        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建HttpGet对象，设置url访问地址
        HttpGet httpGet = new HttpGet(uri);

        // 设置header
        if (null != headerMap && headerMap.size()>0){
            headerMap.forEach((key, value) -> {
                httpGet.addHeader(key, value);
            });
        }

        CloseableHttpResponse response = null;
        String content = null;
        try {
            //使用HttpClient发起请求，获取response
            response = httpClient.execute(httpGet);

            //解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                content = EntityUtils.toString(response.getEntity(), "utf8");
                return content;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return content;
        }
    }

}
